package com.ruoyi.framework.handler;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.constant.GenConstants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;

/**
 * 元数据处理
 *
 * @author Nottyjay
 * @date 2020-10-10
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Timestamp time = new Timestamp(System.currentTimeMillis());
        LoginUser user = SecurityUtils.getLoginUserOrNull();
        this.setFieldValByName("createTime", time, metaObject);
        this.setFieldValByName("createBy", StrUtil.toString(null == user ? "1" : user.getUserId()), metaObject);
        this.setFieldValByName("updateTime", time, metaObject);
        this.setFieldValByName("updateBy", StrUtil.toString(null == user ? "1" : user.getUserId()), metaObject);
        // 若deleted值不存在时进行填充
        if (metaObject.getValue(GenConstants.DELETED_COL) == null) {
            this.setFieldValByName(GenConstants.DELETED_COL, 0, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Timestamp time = new Timestamp(System.currentTimeMillis());
        LoginUser user = SecurityUtils.getLoginUserOrNull();
        this.setFieldValByName("updateTime", time, metaObject);
        this.setFieldValByName("updateBy", StrUtil.toString(null == user ? "1" : user.getUserId()), metaObject);
    }
}
